/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network;

import java.io.IOException;
import java.util.*;

public class StdRoundRobinCoordinator extends StdFailOverCoordinator {
	public final static String COORDINATOR_NAME = "StdRoundRobinCoordinator";
	
	protected static class Context implements ICoordinatorContext {
		private int roundRobinCounter = 0;
		
		public int updateRoundRobinCounter(int maxCounterValue) {
			if(roundRobinCounter >= maxCounterValue) {
				roundRobinCounter = 0;
			}
			return roundRobinCounter++;
		}

		@Override
		public void reset() {			
		}
	}
	
	@Override
	protected synchronized void insertHandler(IManagedConnection connection, ConnectionHandler handler) {
		super.insertHandler( connection, handler );
		if(connection.getCoordinatorContext() == null) {
			connection.setCoordinatorContext(new Context());
		}
		else
			connection.getCoordinatorContext().reset();
	}	
		
	@Override
	public synchronized ConnectionHandler getConnectionHandlerToSend (IManagedConnection managedConnection ) throws IOException {
		Context coordinatorContext = (Context)managedConnection.getCoordinatorContext();		
		if(coordinatorContext == null) {
			throw new InternalError("Unable to found StdRoundRobinCoordinator.Context for connection");
		}
		Set<ConnectionHandler> handlersPerConnection = connections.get(managedConnection);
		if(handlersPerConnection!=null && !handlersPerConnection.isEmpty()) {			
			int handlerCnt=coordinatorContext.updateRoundRobinCounter ( handlersPerConnection.size() );			
			ConnectionHandler handler = null;
			Iterator<ConnectionHandler > it = handlersPerConnection.iterator();
			int i=0;
			do {
				handler = it.next();
			}
			while(++i <= handlerCnt);
			return handler;
		}
		else
			throw new IOException("Unable to found any available connections to send");
	}

	@Override
	public String getName() {
		return COORDINATOR_NAME;
	}

}
